package com.nanohadoop.mapreduce.handler;

import com.nanohadoop.mapreduce.core.Reducer;
import com.nanohadoop.mapreduce.core.ReducerContext;

import java.io.IOException;
import java.util.Iterator;

/**
 * WordCount示例的Reducer实现
 */
public class WordCountReducer extends Reducer<String, Integer, String, Integer> {
            @Override
            public void reduce(String key, Iterator<Integer> values, ReducerContext<String, Integer, String, Integer> context)
                throws IOException, InterruptedException {
            // 校验参数
            if (key == null) {
                throw new IllegalArgumentException("Key cannot be null");
            }
            if (values == null) {
                throw new IllegalArgumentException("Values iterator cannot be null");
            }
            
            int sum = 0;
            while (values.hasNext()) {
                Integer value = values.next();
                if (value == null) {
                    throw new IllegalArgumentException("Values cannot contain null");
                }
                sum += value;
            }
            context.write(key, sum);
        }

}